import { DirectiveBinding, VNode } from 'vue';

const isDescendant = (child: Element, ancestor: Element) => {
  if (child === ancestor) {
    return true
  }
  var node = child.parentNode;
  while (node != null) {
    if (node === ancestor) {
      return true;
    }
    node = node.parentNode;
  }
  return false;
}
const handlerClick = (e: Event, binding: DirectiveBinding, el: Element) => {
  const fn = binding.value
  if (isDescendant(e.target as Element, el)) {
    fn(true)
  } else {
    fn(false)
  }
}
export default {
  name: 'outsider',
  mounted(el: Element, binding: DirectiveBinding, vnode: VNode) {
    window.addEventListener('click', (e: Event) => {
      handlerClick(e, binding, el)
    })
  },
  unmounted(el: Element, binding: DirectiveBinding, vnode: VNode) {
    window.removeEventListener('click', (e: Event) => { handlerClick(e, binding, el) })
  }
}
